package com.xiaoxing.paimai.mvp.ui.fragment;

import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.DividerItemDecoration;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.jess.arms.base.BaseFragment;
import com.jess.arms.di.component.AppComponent;
import com.jess.arms.utils.ArmsUtils;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.constant.SpinnerStyle;
import com.scwang.smartrefresh.layout.header.ClassicsHeader;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import com.xiaoxing.paimai.R;
import com.xiaoxing.paimai.di.component.DaggerKuCunLieBiaoComponent;
import com.xiaoxing.paimai.di.module.KuCunLieBiaoModule;
import com.xiaoxing.paimai.mvp.contract.KuCunLieBiaoContract;
import com.xiaoxing.paimai.mvp.presenter.KuCunLieBiaoPresenter;
import com.xiaoxing.paimai.mvp.ui.activity.ZiZhuCunQuGuiMainActivity;
import com.xiaoxing.paimai.mvp.ui.adapter.KuCunLieBiaoAdapter;
import com.xiaoxing.paimai.mvp.ui.entity.InfoInventory;
import com.xiaoxing.paimai.mvp.ui.entity.KuCunLieBiao;
import com.xiaoxing.paimai.mvp.ui.inter.ScanI;

import org.ksoap2.SoapEnvelope;
import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapPrimitive;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.ksoap2.transport.HttpTransportSE;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import me.jessyan.armscomponent.commonsdk.core.BaseConstants;

import static android.support.v7.widget.DividerItemDecoration.VERTICAL;
import static com.jess.arms.utils.Preconditions.checkNotNull;


public class KuCunLieBiaoFragment extends BaseFragment<KuCunLieBiaoPresenter> implements KuCunLieBiaoContract.View, OnRefreshListener, ScanI {


    private static boolean mIsNeedDemo = true;
    @BindView(R.id.empty_text)
    TextView empty_text;
    @BindView(R.id.empty_image)
    ImageView empty_image;

    @BindView(R.id.empty)
    View mEmptyLayout;
    @BindView(R.id.recyclerView)
    RecyclerView mRecyclerView;
    @BindView(R.id.refreshLayout)
    RefreshLayout mRefreshLayout;
    private KuCunLieBiaoAdapter mAdapter;
    private List<KuCunLieBiao.DataBean> mDataBeanList = new ArrayList<>();

    public static KuCunLieBiaoFragment newInstance() {
        KuCunLieBiaoFragment fragment = new KuCunLieBiaoFragment();
        return fragment;
    }

    @Override
    public void onResume() {
        super.onResume();
    }


    @Override
    public void setupFragmentComponent(@NonNull AppComponent appComponent) {
        DaggerKuCunLieBiaoComponent //如找不到该类,请编译一下项目
                .builder()
                .appComponent(appComponent)
                .kuCunLieBiaoModule(new KuCunLieBiaoModule(this))
                .build()
                .inject(this);
    }

    @Override
    public View initView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_ku_cun_lie_biao, container, false);
    }

    @Override
    public void initData(@Nullable Bundle savedInstanceState) {
        ((ZiZhuCunQuGuiMainActivity) this.getActivity()).registerMyScanIKuCunListener(this);
        initRefreshLayout();
        initRecyclerView();
        initEmpty();
        infoInventory = new InfoInventory(getActivity());

        getInventory("0");

    }

    private void initRefreshLayout() {
        mRefreshLayout.setRefreshHeader(new ClassicsHeader(getActivity()).setSpinnerStyle(SpinnerStyle.FixedBehind).setPrimaryColorId(R.color.public_colorPrimary).setAccentColorId(android.R.color.white));
        mRefreshLayout.setOnRefreshListener(this);
//        mRefreshLayout.autoRefresh();
        mRefreshLayout.setEnableRefresh(false);
        mRefreshLayout.setEnableLoadMore(false);
    }

    private void initRecyclerView() {
        mRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
        mRecyclerView.addItemDecoration(new DividerItemDecoration(getActivity(), VERTICAL));
        mRecyclerView.setItemAnimator(new DefaultItemAnimator());
        mRecyclerView.setAdapter(mAdapter = new KuCunLieBiaoAdapter(getActivity(), list_InfoInventory));

        mAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
            }
        });
    }

    private void initEmpty() {
        empty_image.setImageResource(R.drawable.ic_empty);
        empty_text.setTextColor(Color.parseColor("#DCDCDC"));
        empty_text.setText("暂无数据");
    }


    @Override
    public void setData(@Nullable Object data) {

    }

    @Override
    public void onRefresh(@NonNull RefreshLayout refreshLayout) {

        mRefreshLayout.finishRefresh();

    }

    @Override
    public void showLoading() {

    }

    @Override
    public void hideLoading() {

    }

    @Override
    public void showMessage(@NonNull String message) {
        checkNotNull(message);
        ArmsUtils.snackbarText(message);
    }

    @Override
    public void launchActivity(@NonNull Intent intent) {
        checkNotNull(intent);
        ArmsUtils.startActivity(intent);
    }

    @Override
    public void killMyself() {

    }

    private InfoInventory infoInventory = null;
    List<InfoInventory> list_InfoInventory = new ArrayList<>();
    private static final int STOP = 0;
    private static final int THREADING = 1;
    private static final int POSTSUCCESS = 2;
    private static final int POSTERROR = 3;
    Handler hanlder = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case STOP:
                    mAdapter.notifyDataSetChanged();
                    mEmptyLayout.setVisibility(View.GONE);

                    break;
                case THREADING:
                    list_InfoInventory.clear();
                    mAdapter.notifyDataSetChanged();
                    mEmptyLayout.setVisibility(View.VISIBLE);
                    break;
                case POSTSUCCESS:
                    break;
                case POSTERROR:
                    break;
            }
        }
    };

    @Override
    public void getKuCunOrChuKuList(String spid) {

        getInventory(spid);

    }

    private void getInventory(String spid) {
        new Thread() {
            @Override
            public void run() {

                GetListInfoByQRCodeMidFromWebService(
                        spid, "1");

                if (list_InfoInventory.size() > 0) {
                    Message m = new Message();
                    m.what = STOP;
                    hanlder.sendMessage(m);
                } else {
                    Message m = new Message();
                    m.what = THREADING;
                    hanlder.sendMessage(m);
                }

            }
        }.start();
    }

    private String getSpPort() {
        return mSharedPreferencesHelper.getString(BaseConstants.SHE_ZHI_PORT);
    }

    private String getSpIP() {
        return mSharedPreferencesHelper.getString(BaseConstants.SHE_ZHI_IP);
    }

    // 获取基本信息
    private List<InfoInventory> GetListInfoByQRCodeMidFromWebService(
            String sid, String page) {

        List<InfoInventory> list = null;
        try {
            /****************** 调用webService ***********************/
            // 调用.net 的WebService.
            String nameSpace = "http://tempuri.org/";
//            String methodName = "getInventoryBysid";
            String methodName = "getInventory";

            String url = "http://" + getSpIP() + ":"
                    + getSpPort()
                    + "/ws/ContainerService.asmx";
            String soapAction = nameSpace + methodName;

            // 设置连接参数
            SoapObject request = new SoapObject(nameSpace, methodName);

            // 增加属性参数。 将相关的函数参数放入到过程中。
            request.addProperty("spid", sid);
            request.addProperty("page", page);

            SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(
                    SoapEnvelope.VER11);// soap协议版本必须用SoapEnvelope.VER11（Soap
            // V1.1）;

            // 注意：这个属性是对dotnetwebservice协议的支持,如果dotnet的webservice
            // 不指定rpc方式则用true否则要用false
            envelope.dotNet = true;

            // envelope.setOutputSoapObject(request);//设置请求参数
            envelope.bodyOut = request; // enveloper.bodyOut=request 与
            // envelope.setOutputSoapObject(request)
            // 效果相同。
            // step4 创建HttpTransportSE对象
            HttpTransportSE ht = new HttpTransportSE(url);
            // step5 调用WebService
            ht.call(soapAction, envelope); // 关键的一步，很多问题都在这一步调试时出现问题。要么是IIS有问题，要么是ksoap2相关参数没配置好。
            if (envelope.getResponse() != null) {
                SoapPrimitive response = (SoapPrimitive) envelope.getResponse();

                String returnStr = response.toString();

                if ("" != returnStr) {
                    returnStr = returnStr.substring(returnStr.lastIndexOf("["),
                            returnStr.length());

                    returnStr = returnStr.replace("\\", "");

                    list = infoInventory.getListFromJSON(returnStr);

                    list_InfoInventory.clear();
                    list_InfoInventory.addAll(list);
                }

            }
            /****************** 调用webService结束 ***********************/

        } catch (Exception e) {
            e.printStackTrace();
        }

        return list;
    }

}
